<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会计期" prop="accountingPeriod">
        <el-date-picker clearable
          v-model="queryParams.accountingPeriod"
          type="month"
          value-format="yyyy-MM"
          placeholder="请选择会计期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="编码" prop="allocateCode">
        <el-input
          v-model="queryParams.allocateCode"
          placeholder="请输入编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.financial_allocate_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['financial:allocate:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['financial:allocate:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['financial:allocate:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['financial:allocate:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="allocateList" @selection-change="handleSelectionChange">
      <el-table-column label="代码" align="center" prop="allocateCode" />
      <el-table-column label="会计期" align="center" prop="accountingPeriod" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.accountingPeriod, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type" >
        <template slot-scope="scope">
        <dict-tag :options="dict.type.financial_allocate_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0" type="danger">未处理</el-tag>
          <el-tag v-if="scope.row.status==1" type="success">已处理</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="createBy" />
      <el-table-column label="操作时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['financial:allocate:do']"
          >成本分配</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['financial:allocate:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改成本分配对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="代码" prop="allocateCode">
              <el-input v-model="form.allocateCode" placeholder="请输入代码" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                v-if="optType == 'save' "
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会计期" prop="accountingPeriod">
              <el-date-picker clearable
                              v-model="form.accountingPeriod"
                              type="month"
                              format="yyyy-MM"
                              :picker-options="pickerOptions"
                              value-format="yyyy-MM"
                              placeholder="请选择会计期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="类型" prop="type">
             <el-select v-model="form.type" placeholder="请选择类型" clearable size="small">
               <el-option
                 v-for="dict in dict.type.financial_allocate_type"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
               />
             </el-select>
           </el-form-item>
         </el-col>
       </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAllocate, getAllocate, delAllocate, addAllocate, updateAllocate } from "@/api/mes/financial/allocate";
import {genCode} from "@/api/system/autocode/rule";

export default {
  name: "Allocate",
  dicts:['financial_allocate_type'],
  data() {
    return {
      pickerOptions: {
        disabledDate: (time) => {
          const lastYear = new Date();
          lastYear.setFullYear(lastYear.getFullYear() - 1); // 1年前的时间
          // 获取当前年月（如 2023-11）
          const currentYear = new Date().getFullYear();
          const currentMonth = new Date().getMonth() ; // 月份从0开始，需+1

          // 将当前年月转换为时间戳（当月1日 00:00:00）
          const currentMonthFirstDay = new Date(currentYear, currentMonth - 1, 1).getTime();

          return time > currentMonthFirstDay || time < lastYear;
        }
      },
      autoGenFlag:false,
      optType: "save",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成本分配表格数据
      allocateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        accountingPeriod: null,        allocateCode: null,        type: null,        status: null      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    autoGenFlag: function (val) {
      this.$nextTick(() => {
        this.handleAutoGenChange(val)
      });
    },
  },
  methods: {
    //自动生成编号
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('ALLOCATION_CODE').then(response => {
          this.form.allocateCode = response;
        });
      } else {
        this.form.allocateCode = null;
      }
    },
    /** 查询成本分配列表 */
    getList() {
      this.loading = true;
      listAllocate(this.queryParams).then(response => {
        this.allocateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.autoGenFlag=false;
      this.form = {
        allocateId: null,        deleteFlag: null,        createBy: null,        createTime: null,        updateBy: null,        updateTime: null,        remark: null,        attr1: null,        attr2: null,        attr3: null,        attr4: null,        accountingPeriod: null,        allocateCode: null,        type: null,        status: 0      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.allocateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleView(){
      this.reset();
      this.optType = "view";
      this.open = true;
      this.title = "成本分配";
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.optType = "save";
      this.autoGenFlag=true;
      this.open = true;
      this.title = "添加成本分配";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.optType = "edit";
      const allocateId = row.allocateId || this.ids
      getAllocate(allocateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改成本分配";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.allocateId != null) {
            updateAllocate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAllocate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const allocateIds = row.allocateId || this.ids;
      this.$modal.confirm('是否确认删除成本分配编号为"' + allocateIds + '"的数据项？').then(function() {
        return delAllocate(allocateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('financial/allocate/export', {
        ...this.queryParams
      }, `allocate_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
